package com.block.merchant.service.infotype;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.block.common.annotate.RedisLock;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.ISourcePushResultInfoCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.factory.PushApiFactory;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.db.entity.*;
import com.block.db.mapper.DataMatchOrderInfoMapper;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MemberSourceInfoMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import com.block.merchant.model.dto.MerchantOrderDTO;
import com.block.merchant.model.dto.PushSettleDTO;
import com.block.merchant.model.result.DataPushResult;
import com.block.merchant.model.result.MatchMerchantInfo;
import com.block.merchant.service.IMerchantBaseInfoService;
import com.block.merchant.service.IMerchantDataNoticeLogService;
import com.block.merchant.service.IMerchantDataPushInfoService;
import com.block.merchant.service.IMerchantHandleService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

@Service
public class MerchantApiBHandleService implements IMerchantHandleService {

    private static final Logger log = LogFactory.getMerchantLog();

    @Autowired
    IMerchantDataPushInfoService merchantDataPushInfoService;
    @Resource
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    IMerchantBaseInfoService merchantBaseInfoService;
    @Resource
    MemberSourceInfoMapper memberSourceInfoMapper;
    @Autowired
    IMerchantDataNoticeLogService merchantDataNoticeLogService;
    @Autowired
    ISourcePushResultInfoCommonService sourcePushResultInfoCommonService;
    @Resource
    DataMatchOrderItemMapper dataMatchOrderItemMapper;
    @Resource
    DataMatchOrderInfoMapper dataMatchOrderInfoMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 商户信息匹配
     * @return
     */
    @Override
    public MatchMerchantInfo matchWithMerchant(MerchantBaseInfo merchantBaseInfo, MerchantOrderDTO merchantOrderDTO, MemberSourceInfo memberSourceInfo) throws Exception {

        MatchMerchantInfo matchMerchantInfo =  new MatchMerchantInfo();
        matchMerchantInfo.setMatchSuccess(false);

        matchMerchantInfo.setInfoId(merchantOrderDTO.getInfoId());
        matchMerchantInfo.setInfoType(merchantOrderDTO.getInfoType());
        matchMerchantInfo.setShowPosition(merchantOrderDTO.getShowPostion());

        matchMerchantInfo.setTaskId(merchantOrderDTO.getTaskId());
        matchMerchantInfo.setProfitAmount(merchantOrderDTO.getPriceAmount());
        matchMerchantInfo.setApproveFlag(0);

        matchMerchantInfo.setCompanyName(merchantBaseInfo.getCompanyName());
        matchMerchantInfo.setCompanyLogo(merchantBaseInfo.getCompanyLogo());
        matchMerchantInfo.setMaxLoanAmount(merchantBaseInfo.getMaxLoanAmount());
        matchMerchantInfo.setMaxRate(merchantBaseInfo.getMaxRate());
        matchMerchantInfo.setMinRate(merchantBaseInfo.getMinRate());

        /**
         * 生成匹配记录
         */
        MerchantDataPushInfo dataPushInfo = merchantDataPushInfoService.saveInitPushData(memberSourceInfo, merchantOrderDTO);

        String orderNo = String.valueOf(dataPushInfo.getId());
        PushApiKeyParam pushApiKeyParam = merchantDataPushInfoService.getPushKeyInfo(merchantBaseInfo, memberSourceInfo);
        // 设置授权协议地址
        matchMerchantInfo.setProtocolUrl(pushApiKeyParam.getProtocolUrl());
        matchMerchantInfo.setPushId(orderNo);

        JSONObject extJson = new JSONObject();

        IPushApiService pushApiService = PushApiFactory.getService(merchantBaseInfo.getFactoryType());

        // 进行撞库操作
        PushApiResult pushApiResult = pushApiService.checkUser(orderNo, pushApiKeyParam, memberSourceInfo, extJson);
        if (pushApiResult.getExtJson() != null){
            extJson = pushApiResult.getExtJson();
        }

        log.info("【APIB商户信息匹配】uv 撞库结果【pushApiResult】{}【orderNo】{}【uid】{}", JSON.toJSONString(pushApiResult), orderNo, memberSourceInfo.getUid());
        MerchantDataPushInfo updateEntity = new MerchantDataPushInfo();
        updateEntity.setId(dataPushInfo.getId());
        updateEntity.setParamInfo(pushApiResult.getParamInfo());
        updateEntity.setCode(pushApiResult.getCode());
        updateEntity.setMessage(pushApiResult.getMessage());
        updateEntity.setResultInfo(pushApiResult.getResultInfo());
        updateEntity.setOutOrderNo(pushApiResult.getOutOrderNo());
        updateEntity.setApproveUrl(pushApiResult.getApproveUrl());
        updateEntity.setExtJson(JSON.toJSONString(extJson));

        // 撞库失败，直接更新撞库失败结果
        if (!pushApiResult.isPushSuccess()){
            // 推送失败  更新推送结果
            updateEntity.setStatus(PushStatusEnum.MATCH_FAILED.getValue());
            boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);
            log.info("【APIB商户信息匹配】撞库失败，更新订单结果【updateRes】{}【orderNo】{}【uid】{}",
                    updateRes, orderNo, memberSourceInfo.getUid());
            return matchMerchantInfo;
        }

        // 需要跳转授权地址
        matchMerchantInfo.setApproveFlag(1);

        String approveUrl = pushApiResult.getApproveUrl();
        if (StrUtil.isNotEmpty(approveUrl)){
            // 撞库结果返回了跳转地址
            matchMerchantInfo.setApproveUrl(pushApiResult.getApproveUrl());
            updateEntity.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);

            log.info("【APIB商户信息匹配】APIB类型机构，撞库返回链接，撞库成功，更新订单结果【updateRes】{}【orderNo】{}【uid】{}",
                    updateRes, orderNo, memberSourceInfo.getUid());
            matchMerchantInfo.setMatchSuccess(true);
            return matchMerchantInfo;
        }else{
            // 如果撞库返回的授权跳转地址为空，则根据获取授权方法获取
            // 进行撞库操作
            PushApiResult queryApproveResult = pushApiService.queryApprove(orderNo, pushApiKeyParam, memberSourceInfo, extJson);

            updateEntity.setCode(queryApproveResult.getCode());
            updateEntity.setMessage(queryApproveResult.getMessage());
            updateEntity.setResultInfo(queryApproveResult.getResultInfo());
            updateEntity.setOutOrderNo(queryApproveResult.getOutOrderNo());

            updateEntity.setApproveUrl(queryApproveResult.getApproveUrl());
            updateEntity.setApproveFlag(1);

            if (!queryApproveResult.isPushSuccess()){
                // 获取授权地址失败
                updateEntity.setStatus(PushStatusEnum.GET_APPROVE_FAILED.getValue());
                matchMerchantInfo.setMatchSuccess(false);
            }else{
                updateEntity.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());

                matchMerchantInfo.setMatchSuccess(true);
                matchMerchantInfo.setApproveUrl(queryApproveResult.getApproveUrl());
            }
            boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);
            log.info("【APIB商户信息匹配】获取授权结果，更新订单结果【updateRes】{}【orderNo】{}【uid】{}【matchMerchantInfo】{}",
                    updateRes, orderNo, memberSourceInfo.getUid(), JSON.toJSONString(matchMerchantInfo));
            return matchMerchantInfo;
        }
    }

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public DataPushResult pushToMerchant(MerchantOrderDTO merchantOrderDTO, MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) throws Exception {

        MerchantDataPushInfo merchantDataPushInfo = merchantDataPushInfoMapper.getEntityByOrderNoLock(String.valueOf(merchantOrderDTO.getPushPoolId()));
        JSONObject extJson = new JSONObject();
        if (StrUtil.isNotEmpty(merchantDataPushInfo.getExtJson())){
            extJson = JSON.parseObject(merchantDataPushInfo.getExtJson());
        }

        extJson.put("orderId", String.valueOf(merchantOrderDTO.getOrderId()));
        extJson.put("orderItemId", String.valueOf(merchantOrderDTO.getOrderItemId()));

        PushApiKeyParam pushApiKeyParam = merchantDataPushInfoService.getPushKeyInfo(merchantBaseInfo, memberSourceInfo);
        String orderNo = String.valueOf(merchantDataPushInfo.getId());
        PushApiResult pushApiResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                .registerUser(orderNo, merchantDataPushInfo.getOutOrderNo(), pushApiKeyParam, memberSourceInfo, extJson);
        log.info("【APIB商户信息匹配】推送结果【pushApiResult】{}【orderNo】{}【uid】{}", JSON.toJSONString(pushApiResult), orderNo, memberSourceInfo.getUid());

        if (ObjectUtil.hasEmpty(pushApiResult.getStatus(), pushApiResult.isPushSuccess(), pushApiResult.isSettleFlag())){
            throw new RuntimeException("状态/推送状态/结算标志有空值");
        }

        MerchantDataPushInfo updateEntity = new MerchantDataPushInfo();
        updateEntity.setId(merchantDataPushInfo.getId());
        updateEntity.setUid(memberSourceInfo.getUid());
        updateEntity.setOrderId(merchantOrderDTO.getOrderId());
        updateEntity.setOrderItemId(merchantOrderDTO.getOrderItemId());
        updateEntity.setParamInfo(pushApiResult.getParamInfo());
        updateEntity.setResultInfo(pushApiResult.getResultInfo());
        updateEntity.setCode(pushApiResult.getCode());
        updateEntity.setMessage(pushApiResult.getMessage());
        updateEntity.setStatus(pushApiResult.getStatus());
        updateEntity.setOutOrderNo(pushApiResult.getOutOrderNo());

        boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);
        log.info("【APIB商户信息匹配】更新推送结果【updateRes】{}【orderNo】{}", updateRes, orderNo);

        DataPushResult dataPushResult = new DataPushResult();
        dataPushResult.setPushSuccess(pushApiResult.isPushSuccess());
        dataPushResult.setSettleFlag(pushApiResult.isSettleFlag());
        dataPushResult.setPushOrderId(String.valueOf(merchantDataPushInfo.getId()));

        return dataPushResult;
    }


    /**
     * 查询待
     * 商户通知 ，进件结果
     */
    @Async
    public CompletableFuture<JSONObject> noticePushDataResult(String infoId, Map<String, String[]> parameterMap, String paramContent) throws Exception {

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);

        MerchantDataNoticeLog noticeLog = merchantDataNoticeLogService.saveMerchantNoticeInfo("RESULT", merchantBaseInfo, JSON.toJSONString(parameterMap), paramContent);

        // 根据请求对象，拿到请求数据
        NoticeParamDTO noticeParamDTO = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                .getNoticeResultParam(infoId, parameterMap, paramContent);

        MerchantDataPushInfo merchantDataPushInfo = noticeParamDTO.getMerchantDataPushInfo();

        //判断是否已经通过，状态判断
        if (ObjectUtil.isEmpty(merchantDataPushInfo) || PushStatusEnum.CALLBACK_FAILED.getValue().equals(noticeParamDTO.getStatus())){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("status", "001");
            jsonObject.put("message", "回调失败");
            return CompletableFuture.completedFuture(jsonObject);
        }

        MerchantDataPushInfo updateEntity = new MerchantDataPushInfo();
        updateEntity.setId(merchantDataPushInfo.getId());
        updateEntity.setStatus(noticeParamDTO.getStatus());
        updateEntity.setQueryResult(noticeParamDTO.getQueryResult());
        boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);

        //修改子订单状态
        DataMatchOrderItem dataMatchOrderItem = new DataMatchOrderItem();
        dataMatchOrderItem.setInfoId(Integer.valueOf(infoId));
        dataMatchOrderItem.setPushId(String.valueOf(merchantDataPushInfo.getId()));
        dataMatchOrderItem.setStatus(noticeParamDTO.getStatus());
        boolean i = dataMatchOrderItemMapper.updateDataMatchOrderItemStatus(dataMatchOrderItem);

        DataMatchOrderItem dataMatchOrderItemOne = dataMatchOrderItemMapper.selectDataMatchOrderItemStatus(String.valueOf(merchantDataPushInfo.getId()),infoId);

        //修改订单状态
        DataMatchOrderInfo dataMatchOrderInfo = new DataMatchOrderInfo();
        dataMatchOrderInfo.setId(dataMatchOrderItemOne.getOrderId());
        dataMatchOrderInfo.setStatus(noticeParamDTO.getStatus());
        dataMatchOrderInfoMapper.updateById(dataMatchOrderInfo);


        if (noticeParamDTO.isSettleFlag()){

            // 账户结算
            PushSettleDTO pushSettleDTO = new PushSettleDTO();
            pushSettleDTO.setPushFlag(false);// 此处只统计推送成功的量，为了不重复统计，故此处给false
            pushSettleDTO.setSettleFlag(noticeParamDTO.isSettleFlag());
            pushSettleDTO.setSettleAmount(merchantDataPushInfo.getPriceAmount());

            pushSettleDTO.setChannelCode(merchantDataPushInfo.getChannelCode());

            pushSettleDTO.setInfoId(merchantBaseInfo.getId());
            pushSettleDTO.setInfoName(merchantBaseInfo.getInfoName());
            pushSettleDTO.setInfoType(merchantBaseInfo.getInfoType());
            pushSettleDTO.setTaskId(merchantDataPushInfo.getTaskId());

            pushSettleDTO.setOrderId(String.valueOf(merchantDataPushInfo.getOrderId()));
            pushSettleDTO.setOrderItemId(String.valueOf(merchantDataPushInfo.getOrderItemId()));
            pushSettleDTO.setPushPoolId(String.valueOf(merchantDataPushInfo.getId()));
            MemberSourceInfo memberSourceInfo = new MemberSourceInfo();
            merchantBaseInfoService.handlePushToData(pushSettleDTO,memberSourceInfo);
        }

        JSONObject extObject = new JSONObject();
        extObject.put("uid", merchantDataPushInfo.getUid());

        // 根据请求对象，拿到请求数据
        JSONObject jsonObject = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                .getNoticeResultReturn(parameterMap, paramContent, extObject);

        merchantDataNoticeLogService.updateMerchantNoticeInfo(noticeLog, JSON.toJSONString(jsonObject));

        return CompletableFuture.completedFuture(jsonObject);
    }

    /**
     *
     * 商户通知进件
     * @param infoId
     * @return
     */
    public JSONObject noticeEnterPushData(String infoId, Map<String, String[]> parameterMap, String paramContent) throws Exception {

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);

        MerchantDataNoticeLog noticeLog = merchantDataNoticeLogService.saveMerchantNoticeInfo("ENTER", merchantBaseInfo, JSON.toJSONString(parameterMap), paramContent);

        // 根据请求对象，拿到请求数据
        NoticeParamDTO noticeParamDTO = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                .getNoticeResultParam(infoId, parameterMap, paramContent);

        log.info("【API商户信息匹配】【noticeParamDTO】{}", JSON.toJSONString(noticeParamDTO));

        // 获取推送数据
        MerchantDataPushInfo merchantDataPushInfo = noticeParamDTO.getMerchantDataPushInfo();
        String uid = String.valueOf(merchantDataPushInfo.getUid());

        String redisKey = StrUtil.format(RedisKeyConstant.MERCHANT_NOTICEENTER_PUSHINFO_UID, infoId, uid);
        String pushKey = stringRedisTemplate.opsForValue().get(redisKey);

        if (StrUtil.isEmpty(pushKey) && PushStatusEnum.WAIT_APPROVE.getValue().equals(merchantDataPushInfo.getStatus())){
            stringRedisTemplate.opsForValue().set(redisKey, "1", 6, TimeUnit.HOURS);
            MemberSourceInfo memberSourceInfo = memberSourceInfoMapper.selectById(uid);

            JSONObject extJson = new JSONObject();
            if (StrUtil.isNotEmpty(merchantDataPushInfo.getExtJson())){
                extJson = JSON.parseObject(merchantDataPushInfo.getExtJson());
            }

            PushApiKeyParam pushApiKeyParam = merchantDataPushInfoService.getPushKeyInfo(merchantBaseInfo, memberSourceInfo);
            String orderNo = String.valueOf(merchantDataPushInfo.getId());
            PushApiResult pushApiResult = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                    .registerUser(orderNo, noticeParamDTO.getOutOrderNo(), pushApiKeyParam, memberSourceInfo, extJson);
            log.info("【APIB商户信息匹配】推送结果【pushApiResult】{}【orderNo】{}【uid】{}", JSON.toJSONString(pushApiResult), orderNo, memberSourceInfo.getUid());

            if (ObjectUtil.hasEmpty(pushApiResult.getStatus(), pushApiResult.isPushSuccess(), pushApiResult.isSettleFlag())){
                throw new RuntimeException("状态/推送状态/结算标志有空值");
            }

            MerchantDataPushInfo updateEntity = new MerchantDataPushInfo();
            updateEntity.setId(merchantDataPushInfo.getId());
//        updateEntity.setOrderId(merchantOrderDTO.getOrderId());
//        updateEntity.setOrderItemId(merchantOrderDTO.getOrderItemId());
            updateEntity.setParamInfo(pushApiResult.getParamInfo());
            updateEntity.setResultInfo(pushApiResult.getResultInfo());
            updateEntity.setCode(pushApiResult.getCode());
            updateEntity.setMessage(pushApiResult.getMessage());
            updateEntity.setStatus(pushApiResult.getStatus());
            updateEntity.setOutOrderNo(pushApiResult.getOutOrderNo());

            boolean updateRes = merchantDataPushInfoService.updateById(updateEntity);

            //修改子订单状态
            DataMatchOrderItem dataMatchOrderItem = new DataMatchOrderItem();
            dataMatchOrderItem.setInfoId(Integer.valueOf(infoId));
            dataMatchOrderItem.setPushId(String.valueOf(merchantDataPushInfo.getId()));
            dataMatchOrderItem.setStatus(pushApiResult.getStatus());
            boolean i = dataMatchOrderItemMapper.updateDataMatchOrderItemStatus(dataMatchOrderItem);

            DataMatchOrderItem dataMatchOrderItemOne = dataMatchOrderItemMapper.selectDataMatchOrderItemStatus(String.valueOf(merchantDataPushInfo.getId()),infoId);

            //修改订单状态
            DataMatchOrderInfo dataMatchOrderInfo = new DataMatchOrderInfo();
            dataMatchOrderInfo.setId(dataMatchOrderItemOne.getOrderId());
            dataMatchOrderInfo.setStatus(pushApiResult.getStatus());
            dataMatchOrderInfoMapper.updateById(dataMatchOrderInfo);
            log.info("【APIB商户信息匹配】更新推送结果【updateRes】{}【orderNo】{}", updateRes, orderNo);

            // 账户结算
            PushSettleDTO pushSettleDTO = new PushSettleDTO();
            pushSettleDTO.setPushFlag(pushApiResult.isPushSuccess());// 此处只统计推送成功的量，为了不重复统计，故此处给false
            pushSettleDTO.setSettleFlag(pushApiResult.isSettleFlag());
            pushSettleDTO.setSettleAmount(merchantDataPushInfo.getPriceAmount());

            pushSettleDTO.setChannelCode(merchantDataPushInfo.getChannelCode());

            pushSettleDTO.setInfoId(merchantBaseInfo.getId());
            pushSettleDTO.setInfoName(merchantBaseInfo.getInfoName());
            pushSettleDTO.setInfoType(merchantBaseInfo.getInfoType());
            pushSettleDTO.setTaskId(merchantDataPushInfo.getTaskId());

            pushSettleDTO.setOrderId(String.valueOf(merchantDataPushInfo.getOrderId()));
            pushSettleDTO.setOrderItemId(String.valueOf(merchantDataPushInfo.getOrderItemId()));
            pushSettleDTO.setPushPoolId(String.valueOf(merchantDataPushInfo.getId()));
            merchantBaseInfoService.handlePushToData(pushSettleDTO,memberSourceInfo);
        }

        JSONObject extObject = new JSONObject();
        extObject.put("uid", merchantDataPushInfo.getUid());

        // 根据请求对象，拿到请求数据
        JSONObject jsonObject = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                .getNoticeResultReturn(parameterMap, paramContent, extObject);

        merchantDataNoticeLogService.updateMerchantNoticeInfo(noticeLog, JSON.toJSONString(jsonObject));

        return jsonObject;
    }


    /**
     * 查询待
     * status = WAIT_NOTICE
     */
    public JSONObject noticePullData(String infoId, Map<String, String[]> parameterMap, String paramContent) throws Exception {

        MerchantBaseInfo merchantBaseInfo = merchantBaseInfoService.getById(infoId);

        MerchantDataNoticeLog noticeLog = merchantDataNoticeLogService.saveMerchantNoticeInfo("PULLDATA", merchantBaseInfo, JSON.toJSONString(parameterMap), paramContent);

        JSONObject extObject = new JSONObject();
        extObject.put("infoId", infoId);
        // 根据请求对象，拿到请求数据
        JSONObject jsonObject = PushApiFactory.getService(merchantBaseInfo.getFactoryType())
                .getNoticeResultReturn(parameterMap, paramContent, extObject);

        merchantDataNoticeLogService.updateMerchantNoticeInfo(noticeLog, JSON.toJSONString(jsonObject));

        // 返回信息的处理
        JSONObject returnData = jsonObject.getJSONObject("returnData");
        if (ObjectUtil.isNotEmpty(returnData)){
            return returnData;
        }
        return jsonObject;
    }

    @Override
    public MatchMerchantInfo sourceCheckWithMerchant(MerchantBaseInfo merchantBaseInfo, MerchantOrderDTO merchantOrderDTO, MemberSourceInfo memberSourceInfo) throws Exception {
        throw new RuntimeException("线索撞库异常，线索不进行api回调推送");
    }
}
